<template>
  <div>
    <el-row :gutter="20">
      <el-col :span="8">
        <div class="app-container">
          <el-row class="relationContainer">
            <el-col :span="8"><span class="el-custom-title"
              >工艺组管理</span></el-col>
            <el-col :span="16" style="float:right;">
              <el-button-group style="float: right">
                <el-button
                  type="primary"
                  icon="el-icon-plus"
                  class="el-button--mini"
                  @click="handleCreate"
                  >添加</el-button
                >
                <el-button type="primary"
                 icon="el-icon-edit"
                 size="mini" @click="handleUpdate()">
                  编辑
                </el-button>
                <el-button
                  size="mini"
                  type="danger"
                    icon="el-icon-delete"
                  @click="ui_delete(null, null)"
                >
                  删除
                </el-button>
              </el-button-group>
            </el-col>
          </el-row>
          <el-row type="flex" justify="start">
            <el-tree
              ref="tree2"
              :data="data2"
              :props="defaultProps"
              class="filter-tree"
              default-expand-all
              @node-click="clickNode"
              v-if="this.openPanel"
            />
          </el-row>
        </div>
      </el-col>
      <el-col :span="16">
        <div class="app-container">
          <el-row class="relationContainer">
            <el-col :span="8"><span class="el-custom-title"
              >工艺管理</span></el-col>
            <el-col :span="16" style="float:right;">
              <el-button-group style="float: right">
                <el-button
                  type="primary"
                  icon="el-icon-plus"
                  class="el-button--mini"
                  @click="handleCreateSon"
                  >添加</el-button
                >
                <el-button
                  type="primary"
                  size="mini"
                  icon="el-icon-edit"
                  @click="handleUpdateSon()"
                >
                  编辑
                </el-button>
                <el-button
                  size="mini"
                  type="danger"
                 icon="el-icon-delete"
                  @click="ui_deleteSon(null, null)"
                >
                  删除
                </el-button>
              </el-button-group>
            </el-col>
          </el-row>
          <el-row type="flex" justify="start">
            <el-table
              ref="dataTable"
              v-loading="listLoading"
              :data="list2"
              element-loading-text="Loading"
              border
              fit
              highlight-current-row
              @row-click="rowClick"
              @selection-change="handleSelectionChangeSon"
            >
              >
              <el-table-column type="selection" width="55"></el-table-column>
              <el-table-column
                align="center"
                label="序号"
                width="95"
                v-if="false"
              >
                <template slot-scope="scope">
                  {{ scope.row.id }}
                </template>
              </el-table-column>
              <el-table-column
                align="center"
                label="工艺编号"
                width="95"
                style="display:none;"
              >
                <template slot-scope="scope">
                  {{ scope.row.technologyNo }}
                </template>
              </el-table-column>
              <el-table-column
                align="center"
                label="工艺名称"
                width="95"
                style="display:none;"
              >
                <template slot-scope="scope">
                  {{ scope.row.technologyName }}
                </template>
              </el-table-column>
              <el-table-column
                align="center"
                label="定义"
                width="95"
                style="display:none;"
              >
                <template slot-scope="scope">
                  {{ scope.row.Definition }}
                </template>
              </el-table-column>
              <el-table-column
                align="center"
                label="工艺类型"
                width="95"
                style="display:none;"
              >
                <template slot-scope="scope">
                  {{ scope.row.technologyTypeName }}
                </template>
              </el-table-column>
              <el-table-column
                align="center"
                label="是否启动"
                width="95"
                style="display:none;"
              >
                <template slot-scope="scope">
                  {{ scope.row.enable | resolveEnableValue(scope.row.enable) }}
                </template>
              </el-table-column>
              <el-table-column
                align="center"
                label="备注"
                width="95"
                style="display:none;"
              >
                <template slot-scope="scope">
                  {{ scope.row.comment }}
                </template>
              </el-table-column>
            </el-table>
          </el-row>
          <el-row>
            <pagination
              v-show="total2 > 0"
              :total="total2"
              :page.sync="listQuery2.page"
              :limit.sync="listQuery2.limit"
              :page-sizes="listQuery2.pageSizes"
              @pagination="fetchDataSon"
            />
          </el-row>
        </div>
      </el-col>
    </el-row>
    <el-row>
      <el-tabs type="border-card">
        <el-tab-pane label="标准指导书">
         <mestechnologysoplist :technology = "this.lstSelectedSon[0]" ></mestechnologysoplist>
        </el-tab-pane>
        <el-tab-pane label="工艺动作组">配置管理</el-tab-pane>
        <el-tab-pane label="工艺动作库">角色管理</el-tab-pane>
        <el-tab-pane label="工艺变量">定时任务补偿</el-tab-pane>
        <el-tab-pane label="工艺要求">定时任务补偿</el-tab-pane>
        <el-tab-pane label="观测工时">定时任务补偿</el-tab-pane>
      </el-tabs>
    </el-row>

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="temp"
        label-position="left"
        label-width="120px"
        style="width: 400px; margin-left: 50px"
      >
        <el-form-item label="工段" prop="temp.workSectionId">
          <el-select
            v-model="temp.workSectionId"
            class="filter-item"
            placeholder="请选择工段"
            @change="handleMainTypeChange"
          >
            <el-option
              v-for="item in this.data2.length > 0 &&
              this.data2[0].children != null &&
              this.data2[0].children.length > 0
                ? data2[0].children
                : []"
              :key="item.id"
              :label="item.technologySetName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="上级工艺组" prop="temp.parentId">
          <el-select
            v-model="temp.parentId"
            class="filter-item"
            placeholder="请选择工艺组"
            @change="handleMainTypeChange"
          >
            <el-option
              v-for="item in this.ddWorkSets"
              :key="item.id"
              :label="item.technologySetName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="工艺组编号" prop="technologySetNo">
          <el-input v-model="temp.technologySetNo" />
        </el-form-item>
        <el-form-item label="工艺组名称" prop="technologySetName">
          <el-input v-model="temp.technologySetName" />
        </el-form-item>
        <el-form-item label="备注" prop="comment">
          <el-input v-model="temp.comment" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false"> 取消 </el-button>
        <el-button
          type="primary"
          @click="dialogStatus === 'create' ? ui_create() : ui_update()"
        >
          确定
        </el-button>
      </div>
    </el-dialog>
    <el-dialog
      :title="textMap[dialogStatusSon]"
      :visible.sync="dialogFormVisibleSon"
    >
      <el-form
        ref="dataFormson"
        :rules="rulesson"
        :model="tempson"
        label-position="left"
        label-width="120px"
        style="width: 400px; margin-left: 50px"
      >
        <el-form-item label="工艺编号" prop="technologyNo">
          <el-input v-model="tempson.technologyNo" />
        </el-form-item>
        <el-form-item label="工艺名称" prop="technologyName">
          <el-input v-model="tempson.technologyName" />
        </el-form-item>
        <el-form-item label="定义" prop="Definition">
          <el-input v-model="tempson.Definition" />
        </el-form-item>
        <el-form-item label="工艺类型" prop="technologyTypeId">
          <el-select
            v-model="tempson.technologyTypeId"
            class="filter-item"
            placeholder="请选择工艺类型"
          >
            <el-option
              v-for="item in this.ddTechnologyTypes"
              :key="item.id"
              :label="item.technologyTypeName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="是否启动" prop="enable">
          <el-select
            v-model="tempson.enable"
            class="filter-item"
            placeholder="请选择是否启用"
          >
            <el-option
              v-for="item in [{id:false,enable:'不启用'},{id:true,enable:'启用'}]"
              :key="item.id"
              :label="item.enable"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="comment">
          <el-input v-model="tempson.comment" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisibleSon = false"> 取消 </el-button>
        <el-button
          type="primary"
          @click="
            dialogStatusSon === 'create' ? ui_createSon() : ui_updateSon()
          "
        >
          确定
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import Pagination from "@/components/Pagination"; // secondary package based on el-pagination
import request from "@/utils/request";

import {
  getAll,
  getList,
  create,
  update,
  deleteBatch
} from "@/api/mesTechnologySet";

import {
  getAllSon,
  listSon,
  createSon,
  updateSon,
  deleteBatchSon
} from "@/api/mesTechnology";

import { getAll as getAllTechnologyTypes } from '@/api/mesTechnologyType'
import  mestechnologysoplist  from "@/views/technology/mestechnologysoplist";
import * as relation  from "@/api/MesTechnologySetTechnology";

export default {
  components: { Pagination, mestechnologysoplist },
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: "success",
        draft: "gray",
        deleted: "danger"
      };
      return statusMap[status];
    }
  },
  data() {
    return {
      filterText: "",
      data2: [],
      defaultProps: {
        children: "children",
        label: "technologySetName"
      },
      list: null,
      list2: null,
      listLoading: true,
      total2: 0,
      listQuery2: {
        page: 1,
        limit: 6,
        pageSizes: [6, 10, 14]
      },
      currentMesTechnologySetId: 0,
      dialogFormVisible: false,
      dialogStatus: "",
      textMap: {
        update: "编辑",
        create: "创建"
      },
      rules: {
        technologySetNo: [
          {
            required: true,
            message: "工艺组编号不能为空！",
            trigger: "change"
          }
        ],
        technologySetName: [
          {
            required: true,
            message: "工艺组名称不能为空！",
            trigger: "change"
          }
        ],
        workSectionId: [
          {
            required: true,
            message: "所属工段不能为空！",
            trigger: "change"
          }
        ]
      },
      temp: {
        id: undefined,
        technologySetNo: "",
        technologySetName: "",
        workSectionId: 0,
        comment: ""
      },
      //表格變量
      lstSelected: [],
      currentMesTechnologySet: null,
      dialogFormVisibleSon: false,
      dialogStatusSon: "",
      rulesson: {
        technologyNo: [
          {
            required: true,
            message: "工艺编号不能为空！",
            trigger: "change"
          }
        ],
        technologyName: [
          {
            required: true,
            message: "工艺名称不能为空！",
            trigger: "change"
          }
        ],
        Definition: [
          {
            required: true,
            message: "定义不能为空！",
            trigger: "change"
          }
        ],
        technologyTypeId: [
          {
            required: true,
            message: "工艺类型不能为空！",
            trigger: "change"
          }
        ],
        enable: [
          {
            required: true,
            message: "是否启动不能为空！",
            trigger: "change"
          }
        ],
        comment: [
          {
            required: true,
            message: "备注不能为空！",
            trigger: "change"
          }
        ]
      },
      tempson: {
        id: 0,
        technologyNo: "",
        technologyName: "",
        Definition: "",
        technologyTypeId: 0,
        enable: false,
        comment: ""
      },
      //表格變量
      lstSelectedSon: [],
      lstWorkSetctions: [],
      lstParentIds: [],
      openPanel: true,
      ddWorkSets: [],
      ddTechnologyTypes:[]
    };
  },
  filters:{
     resolveEnableValue(p)
     {
        return p?'是':'否'
     }
  },
  watch: {
    filterText(val) {
      this.$refs.tree2.filter(val);
    },
    list2: function() {
      this.$nextTick(function() {
        this.$refs.dataTable.setCurrentRow(this.list2[0])
        this.lstSelectedSon.length = 0;
        this.lstSelectedSon.push(this.list2[0])
      })
    }
  },
  created() {
    this.fetchData();
    this.fetchDataSon(0)
    this.getAllTechnologyTypes()
  },
  methods: {
    handleSelectionChange(val) {
      this.lstSelected = val;
    },
    fetchData() {
      this.data2 = [];
      this.listLoading = true;
      let params = {
        name: ""
      };
      getAll(params).then(response => {
        this.data2.push(response.data);
        this.listLoading = false;
      });
    },
    clickNode(data, node, obj) {
      this.lstSelected = [];
      if (data.parentId == -1) return;
      this.lstSelected.push(data);
      this.temp = Object.assign({}, data);
      let params = {
        technologySetId: data.id,
        page: this.listQuery2.page,
        size: this.listQuery2.limit
      }
      listSon(params).then(response => {
        this.list2 = response.data.records;
        this.total2 = response.data.total;
        this.listLoading = false;
      });
    },
    ui_create() {
      this.$refs["dataForm"].validate(valid => {
        if (valid) {
          this.temp.id = 0; //自增
          if (this.temp.parentId == null) {
            this.temp.parentId = 0;
          }
          create(this.temp).then(() => {
            this.updateTree(false);
            this.dialogFormVisible = false;
             this.$notify({
              title: "Success",
              message: "添加成功！",
              type: "success",
              duration: 2000
            });
          });
        }
      });
    },
    ui_update() {
      this.$refs["dataForm"].validate(valid => {
        if (valid) {
          if (this.temp.parentId == null) {
            this.temp.parentId = 0;
          }
          update(this.temp).then(() => {
            //刷新UI
            this.updateTree(false);
            this.dialogFormVisible = false;
            this.$notify({
              title: "Success",
              message: "修改成功！",
              type: "success",
              duration: 2000
            });
          });
        }
      });
    },
    ui_delete(row, index) {
      if (this.lstSelected == null || this.lstSelected.length === 0) {
        this.$message.error("请先选择要删除的工艺组");
        return;
      }
      let ids = [];
      this.lstSelected.map(function(elm) {
        ids.push(elm.id);
      });
      deleteBatch(ids).then(() => {
        this.updateTree(true);
        this.dialogFormVisible = false;
        this.$notify({
          title: "Success",
          message: "删除成功！",
          type: "success",
          duration: 2000
        });
      });
    },
    resetTemp() {
      this.temp = {
        technologySetNo: "",
        technologySetName: "",
        workSectionId: 0,
        comment: ""
      };
    },
    handleCreate() {
    
      this.resetTemp();
      this.dialogStatus = "create";
      this.dialogFormVisible = true;
      this.$nextTick(() => {
        this.$refs["dataForm"].clearValidate();
      });
    },
    handleUpdate() {
      if (this.lstSelected == null || this.lstSelected.length == 0) {
        this.$message.error("请先选择一条工艺组");
        return;
      }
      this.temp = Object.assign({}, this.lstSelected[0]); // copy obj
      this.getSelParentIdOptions();
      this.dialogStatus = "update";
      this.dialogFormVisible = true;
      this.$nextTick(() => {
        this.$refs["dataForm"].clearValidate();
      });
    },
    handleSelectionChangeSon(val) {
      if(val == null || val.length == 0) return
      this.lstSelectedSon = val;
      const type = this.ddTechnologyTypes.find(v => v.technologyTypeName == val[0].ddTechnologyTypeName)
      if (type != null) {
        this.tempson.technologyTypeId = type.id;
      }
    },
    fetchDataSon() {
      let params = {
        TherbligsTypeId: this.currentMesTechnologySet,
        page: this.listQuery2.page,
        size: this.listQuery2.limit
      };
      return listSon(params).then(response => {
        this.list2 = response.data.records;
        this.total2 = response.data.total;
        this.listLoading = false;
      });
    },
    rowClick(row, column, event) {
      this.lstSelectedSon.length = 0
      this.lstSelectedSon.push(row)
      this.currentMesTechnologySet = row
    },
    resetTempSon() {
      this.tempson = {
        id: 0,
        technologyNo: "",
        technologyName: "",
        Definition: "",
        technologyTypeId: 0,
        enable: false,
        comment: ""
      };
    },
    handleCreateSon() {
       if (this.lstSelected == null || this.lstSelected.length !== 1 || parseInt(this.lstSelected[0].parentId)<0) {
        this.$message.error("请先选择一条标准工艺组");
        return;
      }
      this.resetTempSon();
      this.dialogStatusSon = "create";
      this.dialogFormVisibleSon = true;
      this.$nextTick(() => {
        this.$refs["dataFormson"].clearValidate();
      });
    },
    handleUpdateSon() {
      if (this.lstSelectedSon == null || this.lstSelectedSon.length !== 1) {
        this.$message.error("请先选择一条标准工艺");
        return;
      }
      this.tempson = Object.assign({}, this.lstSelectedSon[0]); // copy obj
      let cur = this.ddTechnologyTypes.find(v=>v.technologyTypeName == this.lstSelectedSon[0].technologyTypeName);
      this.tempson.technologyTypeId = cur != null ? cur.id:0
      this.tempson = { ...this.tempson };
      this.dialogStatusSon = "update";
      this.dialogFormVisibleSon = true;
      this.$nextTick(() => {
        this.$refs["dataFormson"].clearValidate();
      });
    },
    ui_createSon() {
      this.$refs["dataFormson"].validate(valid => {
        if (valid) {
          this.tempson.id = 0; //自增
          createSon(this.tempson).then((response) => {
          
            //主要是为了获得id
           this.tempson.id = response.data
            this.tempson.technologyTypeName = this.ddTechnologyTypes.find(v=>v.id==this.tempson.technologyTypeId).technologyTypeName
            this.list2.unshift(this.tempson);
            this.dialogFormVisibleSon = false;
               //新增关系
            let relationParam = {
               id:0,
               technologyId:this.tempson.id,
               technologySetId:this.lstSelected[0].id
            }
            
            relation.createRelation(relationParam).then(response=>{
              this.$notify({
              title: "Success",
              message: "添加成功！",
              type: "success",
              duration: 2000
            });
            })
            
          });
        }
      });
    },
    ui_updateSon() {
      this.$refs["dataFormson"].validate(valid => {
        if (valid) {
          updateSon(this.tempson).then(() => {
            const index = this.list2.findIndex(v => v.id === this.tempson.id);
            //动态添加name属性
            this.tempson.technologyTypeName = this.ddTechnologyTypes.find(v=>v.id==this.tempson.technologyTypeId).technologyTypeName
            this.list2.splice(index, 1, this.tempson)
            console.log(this.list2)
            //delete  this.tempson.technologyTypeName
            this.dialogFormVisibleSon = false;
            this.$notify({
              title: "Success",
              message: "修改成功！",
              type: "success",
              duration: 2000
            });
          });
        }
      });
    },
    ui_deleteSon(row, index) {
      if (this.lstSelectedSon == null || this.lstSelectedSon.length === 0) {
        this.$message.error("请先选择要删除的工艺");
        return;
      }
      let ids = [];
      this.lstSelectedSon.map(function(elm) {
        ids.push(elm.id);
      });
      deleteBatchSon(ids).then(() => {
        ids.forEach(elm => {
          const index = this.list2.findIndex(v => v.id === elm);
          this.list2.splice(index, 1);
        });
        this.dialogFormVisibleSon = false;
        this.$notify({
          title: "Success",
          message: "删除成功！",
          type: "success",
          duration: 2000
        });
      });
    },
    handleMainTypeChange(val) {
      this.getSelParentIdOptions();
    },
    getSelParentIdOptions() {
      ;
      this.ddWorkSets = [];
      this.ddWorkSets.push({ id: 0, technologySetName: "请选择" });
      //如果没有选中的同工艺组则列出所有的一级工艺组
      if (this.temp.workSectionId > 0) {
        const workset =
          this.data2 != null &&
          this.data2[0].children.find(v => v.id === this.temp.workSectionId);
        if (workset != null && workset.children != null) {
          this.ddWorkSets.push(...workset.children);
        }
      } else {
        if (
          this.data2 != null &&
          this.data2[0].children != null &&
          this.data2[0].children.length > 0
        ) {
          this.data2[0].children.forEach(v => {
            if (v.children != null && v.children.length > 0) {
              this.ddWorkSets.push(...v.children);
            }
          });
        }
      }
    },
    updateTree(isDel) {
      if (isDel && this.temp.id == 0) {
        this.$message.error("数据处于草稿状态，请先刷新页面再删除！");
        return;
      }
      //先找到工段(更新)
      if (
        this.data2 != null &&
        this.data2[0].children != null &&
        this.data2[0].children.length > 0
      ) {
        let worksection = this.data2[0].children.find(
          v => v.id == this.temp.workSectionId
        );
        if (worksection != null) {
          if (this.temp.parentId == 0) {
            //从第三级找
            if (this.temp.id > 0) {
              //更新
              let idx = worksection.children.findIndex(
                v => v.id == this.temp.id
              )
              if (idx >= 0) {
                if (!isDel) {
                  worksection.children.splice(idx, 1, this.temp)
                } //删除
                else {
                  worksection.children.splice(idx, 1)
                }
              }
            } //增加
            else {
              worksection.children.push(this.temp)
            }
          } //从第四级找
          else {
            let parentIdx = worksection.children.findIndex(
              v => v.id == this.temp.parentId
            );
            if (parentIdx >= 0) {
              let parent = worksection.children[parentIdx]
              if (this.temp.id > 0) {
                //更新
                let idx = parent.children.findIndex(v => v.id == this.temp.id);
                if (!isDel) {
                  parent.children.splice(idx, 1, this.temp)
                } //删除
                else {
                  parent.children.splice(idx, 1)
                }
              } //增加
              else {
                parent.children.push(this.temp);
              }
            }
          }
        }
      }
    },
    getAllTechnologyTypes()
    {
         getAllTechnologyTypes().then(response=>{
           this.ddTechnologyTypes.push({id:0,technologyTypeName:'请选择'})
           this.ddTechnologyTypes.push(...response.data);
         })
    },
  }
};
</script>
<style>
.el-row {
  margin-bottom: 20px;
  &:last-child {
    margin-bottom: 0;
  }
}
.el-col {
  border-radius: 4px;
}
.bg-purple-dark {
  background: #99a9bf;
}
.bg-purple {
  background: #d3dce6;
}
.bg-purple-light {
  background: #e5e9f2;
}
.grid-content {
  border-radius: 4px;
  min-height: 36px;
}
.row-bg {
  padding: 10px 0;
  background-color: #f9fafc;
}
</style>
